<template>
  <el-container style="flex-direction:column;position: relative;">
    <el-main style="padding:0;">
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane label="全部订单" name="0"></el-tab-pane>
        <el-tab-pane label="待打印" name="1"></el-tab-pane>
        <el-tab-pane label="待取件" name="2"></el-tab-pane>
        <el-tab-pane label="待配送" name="3"></el-tab-pane>
        <el-tab-pane label="配送完成" name="4"></el-tab-pane>
        <el-tab-pane label="交易完成" name="5"></el-tab-pane> 
        <el-tab-pane label="退款中" name="-1"></el-tab-pane>
        <el-tab-pane label="已退款" name="-2"></el-tab-pane> 
        <el-tab-pane label="退款失败" name="-3"></el-tab-pane> 
      </el-tabs>
      <el-form :inline="true" :model="formInline" size="mini" class="demo-form-inline">
        <el-form-item label="" style="width: 160px;">
          <el-input v-model="formInline.number" placeholder="请输入订单号搜索"></el-input>
        </el-form-item>
        <el-form-item label="" style="width: 140px;">
          <el-select clearable v-model="formInline.storeId" placeholder="请选择门店">
            <el-option
              v-for="item in storeList"
              :key="item.storeId"
              :label="item.name"
              :value="item.storeId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="">
          <el-date-picker
            v-model="formInline.datetime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="success" icon="el-icon-search" @click="onSubmit">搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" icon="el-icon-refresh-left" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table ref="orderTable"
        height="calc(100vh - 288px)"
        @selection-change="selectionChange"
        :data="pagingData.records" size="mini"
        style="width: 100%;">
        <el-table-column align="center" header-align="center"
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column align="center" header-align="center"
          prop="number"
          label="订单号">
        </el-table-column>
        <el-table-column align="center" header-align="center"
          prop="isSelfMention"
          label="订单类型">
          <template slot-scope="scope">
            {{scope.row.isSelfMention==1?"自提":"配送"}}
          </template>
        </el-table-column>
        <el-table-column align="center" header-align="center"
          prop="name"
          label="所属门店">
        </el-table-column>
        <el-table-column align="center" header-align="center"
          prop="storeName"  min-width="220px"
          label="商品信息">
          <template slot-scope="scope">
            <div style="display:flex;flex-direction:column;" >
              <div style="display:flex;justify-content: center;" v-for="s in scope.row.storeOrderCommodityDetailsDTOList" :key="s.commodityDetailsId">
                <img :src="s.image?baseURL+s.image:'#'" style="width:24px;height:24px;">
                <span>{{s.commodityName}}-</span>
                <span v-if="s.isMultiSpecification == 0">
                  默认|
                </span>
                <span v-else>
                  <span v-for="g in s.groupValueList" :key="g.groupValueId">
                    {{g.groupValueName}}
                  </span>
                  <span>|</span>
                </span>
                <span>￥{{s.unitPrice}}</span>
                <span>x{{s.quantity}}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" header-align="center"
          prop="allPrice" 
          label="实际支付">
        </el-table-column>
        <el-table-column align="center" header-align="center"
          prop="statusName"  width="130"
          label="订单状态">
          <template slot-scope="scope">
            {{scope.row.status.desc}}
          </template>
        </el-table-column>
        <el-table-column align="center" header-align="center"
          prop="createTime"  width="180"
          label="创建时间">
           <template slot-scope="scope">
            {{scope.row.createTime | dateYMDHMSFormat}}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="260" align="center" header-align="center" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"  type="primary"
              @click="handleEdit(scope.$index, scope.row)">订单详情</el-button>
             <el-button v-if="scope.row.status.code == 1"
              size="mini"  type="primary"
              @click="print(scope.$index, scope.row)">打印</el-button>
              <el-dropdown split-button type="primary" size="mini" style="margin-left: 10px;">
                操作
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item>
                    <el-button size="mini" type="success"  @click="openOrderRemarkesDialog(scope.row)">订单备注</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button size="mini" type="primary" v-if="scope.row.status.code == 3" @click="deliveryCompleted(scope.row)">配送完成</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button size="mini" type="primary" v-if="scope.row.status.code == 1"  @click="printComplete(scope.row)">打印完成</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button size="mini" type="primary" v-if="scope.row.status.code == -1"  @click="immediateRefund(scope.row)">立即退款</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button size="mini" type="primary" v-if="scope.row.status.code == -1"  @click="refuseRefund(scope.row)">拒绝退款</el-button>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <el-footer style="background-color: #f6f6f6;display:flex;align-items: center;justify-content: space-between;">
      <el-select v-model="caozuo" placeholder="请选择" size="small" style="width:120px" @change="caozuoChange">
        <el-option label="批量操作" value="批量操作"></el-option>
        <el-option label="批量打印订货单" value="批量打印订货单"></el-option>
        <el-option v-if="activeName=='1'" label="批量打印完成" value="批量打印完成"></el-option>
        <el-option v-if="activeName=='3'" label="批量配送完成" value="批量配送完成"></el-option>
      </el-select>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagingData.current"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pagingData.size"
        layout="total, prev, pager, next, sizes,jumper"
        :total="pagingData.total">
      </el-pagination>
    </el-footer>
    <Order_print_dialog
      :visible.sync="visible" 
      :printList="printList"
      @closeDialog="closeDialog"
    ></Order_print_dialog>
    <OrderRemarks
     :orderRemarkesVisible.sync="orderRemarkesVisible"
     :orderRemarkesForm="orderRemarkesForm"
     @closeOrderRemarkesDialog="orderRemarkesVisible = false"
     @orderRemarkesOperationFrom="orderRemarkesOperationFrom"
    ></OrderRemarks>
  </el-container>
</template>
<script>
import OrderRemarks from "./components/OrderRemarks.vue";
import Order_print_dialog from "./components/Order_print_dialog.vue";
import {getPagingStore,updateOrderStautsByOrderId} from '@/api/modules/orderManagement/order.js'
import {getUserHaveOrBelongToStore} from '@/api/modules/StoreManagement/storeList.js'
import { baseURL } from '@/utils/setting.js'
import { Base64 } from 'js-base64';
export default {
  components:{
    Order_print_dialog,
    OrderRemarks
  },
  computed: {
    baseURL() { return baseURL },
  },
  data() {
    return {
      activeName: '0',
      formInline: {
        number: '',
        storeId: '',
        datetime: []
      },
      visible: false,
      printList:[],
      pagingData:{},
      multipleSelection: [],
      size:10,
      current:1,
      storeList:[],
      caozuo:"批量操作",
      orderRemarkesVisible:false,
      orderRemarkesForm:{}
    }
  },
  created() {
    this.getUserHaveOrBelongToStore()
    this.getPagingStore();
  },
  mounted() {
    this.$nextTick(() => {
      this.$refs['orderTable'].doLayout()
    })
  },
  methods: {
    orderRemarkesOperationFrom(){
      this.orderRemarkesVisible = false
      this.getPagingStore();
    },
    openOrderRemarkesDialog(data){
      this.orderRemarkesVisible = true
      let form = {
        orderId:data.orderId,
        number: data.number,
        merchantRemarks:data.merchantRemarks
      }
      this.orderRemarkesForm = form
    },
    immediateRefund(row){
      this.$confirm(`同意订单${row.number}退款?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateOrderStautsByOrderId([{
          orderId:row.orderId,
          status: -2
        }]).then(()=>{
          this.getPagingStore();
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消退款'
        });          
      });
    },
    refuseRefund(row){
       this.$confirm(`拒绝订单${row.number}退款?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateOrderStautsByOrderId([{
          orderId:row.orderId,
          status: -3
        }]).then(()=>{
          this.getPagingStore();
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消拒绝退款'
        });          
      });
    },
    printComplete(row){
      // console.log(row)
      let data = [{
        orderId:row.orderId,
        status: row.isSelfMention ==1?2:3
      }]
      updateOrderStautsByOrderId(data).then(()=>{
        this.getPagingStore();
      })
    },
    deliveryCompleted(row){
      updateOrderStautsByOrderId([{
        orderId:row.orderId,
        status: 4
      }]).then(()=>{
        this.getPagingStore();
      })
    },
    print(index, row){
      // console.log(index, row,row.fileUrl);
      if(!row.fileUrl){
        this.$message({
          message: '该订单上传文件为空，请联系买家！',
          type: 'warning'
        });
        return;
      }
      let nowFileUrl =baseURL+ row.fileUrl
      let url = 'http://127.0.0.1:8012/onlinePreview?url='+encodeURIComponent(Base64.encode(nowFileUrl))
      window.open(url)
    },
    caozuoChange(item){
      this.caozuo = "批量操作"
      if(this.multipleSelection.length == 0){
        this.$message({
          message: '请选择订单！',
          type: 'warning'
        });
        return;
      }
      if(item == "批量打印订货单"){
        this.printList = this.multipleSelection
        this.visible = true
      }
      if(item == "批量打印完成"){
        let data = this.multipleSelection
        let updateOrderStautsDTOList = []
        let numberList = []
        for(let item of data){
          numberList.push(item.number)
          updateOrderStautsDTOList.push({ 
            orderId:item.orderId,
            status: item.isSelfMention ==1?2:3
          })
        }
        this.$confirm(`是否将订单${numberList.join('、')}打印完成?`, '打印', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          updateOrderStautsByOrderId(updateOrderStautsDTOList).then(()=>{
            this.getPagingStore();
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });          
        });
      }
      if(item == '批量配送完成'){
        let data = this.multipleSelection
        let updateOrderStautsDTOList = []
        let numberList = []
        for(let item of data){
          numberList.push(item.number)
          updateOrderStautsDTOList.push({ 
            orderId:item.orderId,
            status: 4
          })
        }
        this.$confirm(`是否将订单${numberList.join('、')}配送完成?`, '配送', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          updateOrderStautsByOrderId(updateOrderStautsDTOList).then(()=>{
            this.getPagingStore();
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });          
        });
      }
    },
    //el-tabs选择事件
    handleClick() {
      // console.log(tab, event);
      this.getPagingStore();
    },
    onSubmit() {
      console.log('submit!');
      this.getPagingStore();
    },
    onReset() {
      // this.$refs["ruleForm"].resetFields();
      this.formInline =  {
        number: '',
        storeId: '',
        datetime: []
      },
      this.getPagingStore();
    },
    handleEdit(index, row) {
      console.log(index, row);
      this.$router.push({ path: `/orderManagement/orderDetails/${row.orderId}` })
    },
    handleDelete(index, row) {
      console.log(index, row);
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.size = val
      this.getPagingStore()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.current = val
      this.getPagingStore()
    },
    selectionChange(val){
      this.multipleSelection = val;
    },
    //关闭dialog
    closeDialog(){
      this.visible=false;
    },
    getUserHaveOrBelongToStore(){
      getUserHaveOrBelongToStore().then(res=>{
        this.storeList = res.data.data
      })
    },
    getPagingStore(){
      let data = {
        size : this.size,
        current : this.current,
        status: parseInt(this.activeName),
        number:this.formInline.number,
        startTime:this.formInline.datetime&&this.formInline.datetime[0]?this.formInline.datetime[0]:null,
        endTime:this.formInline.datetime&&this.formInline.datetime[1]?this.formInline.datetime[1]:null,
        storeId:this.formInline.storeId ? this.formInline.storeId:null
      }
      getPagingStore({storeOrderPagingDTO:JSON.stringify(data)}).then(res=>{
        this.pagingData = res.data.data
        this.$nextTick(() => {
          this.$refs['orderTable'].doLayout()
        })
      })
    },
  } 
}
</script>

<style>

</style>